package com.yunfeisoft.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.applet.utils.Constants;
import com.applet.utils.KeyUtils;
import com.applet.utils.SpringContextHelper;
import com.yunfeisoft.business.model.ProductCategory;
import com.yunfeisoft.business.service.inter.ProductCategoryService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ProductCategoryExcelListener extends AnalysisEventListener<ProductCategory> {

    private static final Logger logger = LoggerFactory.getLogger(ProductCategoryExcelListener.class);

    private List<ProductCategory> list = new ArrayList<ProductCategory>();
    private String orgId;
    private String userId;

    public ProductCategoryExcelListener(String orgId, String userId) {
        this.orgId = orgId;
        this.userId = userId;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param productCategory
     * @param analysisContext
     */
    @Override
    public void invoke(ProductCategory productCategory, AnalysisContext analysisContext) {
        if (StringUtils.isBlank(productCategory.getName())) {
            return;
        }
        productCategory.setId(KeyUtils.getKey());
        productCategory.setOrgId(orgId);
        productCategory.setCreateId(userId);
        productCategory.setModifyId(userId);
        productCategory.setIdPath(productCategory.getId());
        productCategory.setNamePath(productCategory.getName());
        productCategory.setParentId(Constants.ROOT);

        list.add(productCategory);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        ProductCategoryService productCategoryService = SpringContextHelper.getBean(ProductCategoryService.class);
        productCategoryService.batchSave(list);
    }
}
